var timer, cache;
var totcompleted_bytes, totsize, totpercent_complete, totdown_rate, 
    totdown_total, totup_rate, totup_total, totratio, totcount, disk_free;

function init(){
    cache = new Array();
    timer = setInterval('update()', 1000);
}
function updateTimer(sec){
    clearInterval(timer);
    timer = setInterval('update()', sec*1000);
}
function update(){
    new Ajax.Request('ajax-index.php', {onComplete: success, onFailure: failure});
}
function failure(msg){
    //alert(msg);
    refresh();
}
function success(res){
    if (res == null || res.responseText == null || res.responseText == '') refresh();
    var start = new Date().getTime();
    
    try
    {
        var data = res.responseText.evalJSON();
        
        totcompleted_bytes = totsize = totpercent_complete = totdown_rate = 
        totdown_total = totup_rate = totup_total = totratio = totcount = disk_free = 0;
        for (var i = 0; i < data.length; i++){
            var item = data[i];
            if (typeof(cache[item.hash]) == 'undefined') cache[item.hash] = get_statusstyle(item);
            
            if ($(item.hash) != null){
                updateRow(item);
                disk_free = item.free_diskspace;
                //calc totals
                totcompleted_bytes+=item.completed_bytes;
                totsize+=item.size_bytes;
                totpercent_complete+=item.percent_complete;
                totdown_rate+=item.down_rate;
                totdown_total+=item.down_total;
                totup_rate+=item.up_rate;
                totup_total+=item.up_total;
                totratio+=item.ratio
                totcount++;
            }
            else{
                addRow(item);
            }
        }
        $('total.percent').innerHTML = get_percent_str(totpercent_complete/totcount);
        $('total.complete').innerHTML = format_bytes(totcompleted_bytes);
        $('total.size').innerHTML = format_bytes(totsize);
        $('total.down_rate').innerHTML = format_bytes(totdown_rate);
        $('total.down_total').innerHTML = format_bytes(totdown_total);
        $('total.up_rate').innerHTML = format_bytes(totup_rate);
        $('total.up_total').innerHTML = format_bytes(totup_total);
        $('total.ratio').innerHTML = (totratio/totcount/1000).toFixed(2) + ' %';
        
        $('diskfree').innerHTML = format_bytes(disk_free);
    }
    catch (e){
        failure(e.toString());
    }
    var time = new Date().getTime() - start;
    $('pagetime').innerHTML = ' | Page Updated in ' + (time/1000).toFixed(3) + ' sec';
}
function updateRow(item){
    var statusstyle = get_statusstyle(item);
    if (statusstyle != cache[item.hash]){
        var active = item.is_active == 1
        $(item.hash+'.cmd').href = "control.php?hash='" + item.hash + "'&cmd='" + (active ? "stop" : "start") + "'";
        $(item.hash+'.cmd').innerHTML = active ? 
            "<img alt='Stop torrent' border=0 src='images/stop.gif' width=16 height=16>" : 
            "<img alt='Start torrent' border=0 src='images/start.gif' width=16 height=16>";
        $(item.hash+'.status').innerHTML = "<img src='images/"+statusstyle+".gif' width=10 height=9 alt='Status'>" + item.status_string;
    }
    
    $(item.hash+'.eta').innerHTML = get_eta(item);
    $(item.hash+'.percent').innerHTML = get_percent_str(item.percent_complete) + "<br/>\n" + get_percentbar(item.percent_complete);
    $(item.hash+'.complete').innerHTML = format_bytes(item.completed_bytes);
    //$(item.hash+'.size').innerHTML = format_bytes(item.size_bytes);
    $(item.hash+'.down_rate').innerHTML = format_bytes(item.down_rate);
    $(item.hash+'.down_total').innerHTML = format_bytes(item.down_total);
    $(item.hash+'.up_rate').innerHTML = format_bytes(item.up_rate);
    $(item.hash+'.up_total').innerHTML = format_bytes(item.up_total);
    $(item.hash+'.peers').innerHTML = item.peers_connected + "/" + item.peers_not_connected + "(" + item.peers_complete + ")";
    $(item.hash+'.ratio').innerHTML = get_percent_str(item.ratio / 1000);
}
function addRow(item){
}
function removeRow(hash){
}
function refresh(){
    location.reload(true);
}
function format_bytes(bytes){
    var unim = new Array("B","KB","MB","GB","TB","PB");
    var c = 0;
    while (bytes>=1024) {
        c++;
        bytes /= 1024;
    }
    return (c == 0 ? bytes : bytes.toFixed(2)) + unim[c];
}
function get_percent_str(percent){
    return percent.toFixed(2) + ' %';
}
function get_percentbar(percent){
    return  '<table border=0 cellspacing=0 cellpadding=1 bgcolor=#666666 width=50px><tr><td align=left>' +
            "<img src='images/percentbar.gif' height=4px width="+Math.round(percent/2)+"px></td></tr>" +
            "</table>\n";
}
function get_statusstyle(item){
    var statusstyle = (item.complete == 1) ? 'complete' : 'incomplete';
    statusstyle += (item.is_active == 1) ? 'active' : 'inactive';
    return statusstyle;
}
function get_eta(item){
    var eta = '';
    if (item.down_rate > 0){
        var s = (item.size_bytes - item.completed_bytes) / item.down_rate;
        var d = Math.floor(s/86400)
        s %= 86400;
        var h = Math.floor(s/3600);
        s %= 3600;
        var m = Math.floor(s/60);
        s = Math.round(s%60);
        eta += (d > 0 ? d + ' Days, ' : '') + (h >= 10 ? h : '0'+h) + ':' + (m >= 10 ? m : '0'+m) + ':' + (s >= 10 ? s : '0'+s);
    } else if (item.complete == 0 && item.is_active == 1) {
        eta += 'Unknown...';
    }
    return eta;
}
